package com.dmsdbj.itoo.graduate.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.dmsdbj.itoo.graduate.entity.PictureEntity;
import com.dmsdbj.itoo.graduate.facade.PictureFacade;
import com.dmsdbj.itoo.graduate.tool.ResultCode;
import com.dmsdbj.itoo.tool.business.ItooResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;


/**
 * @author sxm
 * DESCRIPTION: graduate展示
 * create: 2017-11-16 14:31:07.
 */
@Api(value = "图片API", tags = "图片API")
@RequestMapping("/picture")
@Controller
public class PictureController {

    //定义打印日志相关
    private static final Logger logger = LoggerFactory.getLogger(PictureController.class);

    @Reference
    PictureFacade pictureFacade;

    /**
     * @author sxm
     * DESCRIPTION:首页导向页
     * @params:
     * @return:
     * @Date:
     * @Modified By:
     */
    @RequestMapping(value = {"/index"}, method = RequestMethod.GET)
    public String index() {
        return "picture";
    }

    /**
     * 根据id查询图片-徐玲博-2018-2-9 16:46:44
     *
     * @param id 图片id
     * @return 图片实体
     */
    @Deprecated
    @ApiOperation(value = "根据id查询图片", notes = "根据id查询图片")
    @RequestMapping(value = {"/findById/{id}"}, method = RequestMethod.GET)
    public ItooResult findById(@PathVariable String id) {
        try {
            PictureEntity pictureEntity = pictureFacade.findById(id);
            if (pictureEntity != null) {
                return ItooResult.build("0000", "查询该课程成功", pictureEntity);
            } else {
                return ItooResult.build("0000", "查询该课程为空");
            }

        } catch (Exception e) {
            logger.error("", e);
            return ItooResult.build("1111", "查询该课程失败");
        }
    }

    /***
     * 图片上传-徐玲博-2018-1-13 15:32:20
     */
    @Deprecated
    @ApiOperation(value = "图片上传方法", notes = "图片上传方法")
    @ResponseBody
    @RequestMapping(value = {"/FileUpload"}, method = RequestMethod.POST)
    public ItooResult uploadPicture(@RequestParam("file") MultipartFile file, HttpSession session, HttpServletRequest request) {
        String backfileUrl = null;
        try {
            if (!file.isEmpty()) {
                // 获得原始文件名
                String fileName = file.getOriginalFilename();
                // 重命名文件
                String newFileName = System.currentTimeMillis() + String.valueOf(fileName);
                //获得物理路径webapp所在路径
//                /**
//                 * request.getSession().getServletContext().getRealPath("/")表示当前项目的根路径，如
//                 * D:\Workspaces\eclipse_luna\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\sky\
//                 */
                String pathRoot = request.getSession().getServletContext().getRealPath("");
                // 项目下相对路径，把生成的文件保存到下面目录下
                String path = "/upload/" + newFileName;
                //获取拓展名
                String fileExtName = fileName.substring(fileName.lastIndexOf('.') + 1);
                // 创建文件实例
                File tempFile = new File(pathRoot + path);
                // 判断父级目录是否存在，不存在则创建
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdir();
                }
                // 判断文件是否存在，否则创建文件（夹）
                if (!tempFile.exists()) {
                    tempFile.mkdir();
                }
                // 把MultipartFile类型转换为file

                file.transferTo(tempFile);

                //生成文件的路径
                String fileUrl = pathRoot + path;
                //把url中的'\'转换为'\\'
                fileUrl = fileUrl.replaceAll("\\\\", "\\\\\\\\");
                //把文件上传到fastdfs
                backfileUrl = pictureFacade.uploadPersonPicture(fileUrl, fileExtName);
            }
            return ItooResult.build(ResultCode.SUCCESS, "图片上传成功！", backfileUrl);
        } catch (Exception e) {
            logger.error("图片上传异常", e);
            return ItooResult.build(ResultCode.FAIL, "图片上传失败！");
        }
    }

    /**
     * 根据与图片表有关表的id，删除图片-徐玲博-2018-2-9 16:16:23
     *
     * @param keyId    例如个人表的userid
     * @param operator 操作人
     * @return 受影行
     */
    @Deprecated
    @ApiOperation(value = "根据keyID删除图片", notes = "根据keyID删除图片")
    @ResponseBody
    @RequestMapping(value = "deletePictureById/{keyId}/{operator}", method = RequestMethod.POST)
    public ItooResult deletePictureById(@PathVariable String keyId, @PathVariable String operator) {
        try {
            int flag = pictureFacade.deletePictureById(keyId, operator);
            if (flag > 0) {
                return ItooResult.build(ResultCode.SUCCESS, "根据id删除图片成功", flag);
            } else {
                return ItooResult.build(ResultCode.FAIL, "图片删除失败");
            }
        } catch (Exception e) {
            logger.error("根据id删除图片异常{}", e);
            return ItooResult.build(ResultCode.FAIL, "根据id删除图片失败");
        }
    }

    /**
     * 根据id查询图片-2018年3月15日11:23:50-xy
     * @param keyId 学历ID
     * @return 图片urls List
     */
    @ApiOperation(value = "根据id查询图片", notes = "根据id查询图片")
    @ResponseBody
    @RequestMapping(value = {"/selectPictureById/{keyId}"}, method = RequestMethod.GET)
    public ItooResult selectPictureById(@PathVariable String keyId){
        try {
            List<String> flag = pictureFacade.selectPictureById(keyId);
            if (!CollectionUtils.isEmpty(flag)) {
                return ItooResult.build(ResultCode.SUCCESS, "根据id查询图片成功", flag);
            } else {
                return ItooResult.build(ResultCode.FAIL, "查询图片为空");
            }
        } catch (Exception e) {
            logger.error("根据id查询图片异常{}", e);
            return ItooResult.build(ResultCode.FAIL, "根据id查询图片失败");
        }
    }
}    
